<?php
/**
 * 文章系统使用到的ajax处理部分
 *
 *
 *
 */
require(dirname(__FILE__) . '/../../includes/global.php');


function get_paramhtml($pid, $typeid, $param_value='', $defvalue='', $cols=0, $rows=0) {
    global $G_cfg;
    $str = '';
    $typeid = @(int)$typeid;
    $param_value    = trim($param_value);



    foreach($G_cfg['article_cfg']['article_paramtype'] as $key => $param) {
        if($key == $typeid) {
            if($param['type'] == 'text') {
                if($cols <= 0) $cols = $param['size'];
                if($param_value == '') $param_value = $defvalue;
                $str = '<INPUT TYPE="text" NAME="param['.$pid.']" VALUE="'.$param_value.'" size="'.$cols.'" class="text">';
            } elseif($param['type'] == 'textarea') {
                if($cols <= 0) $cols = $param['cols'];
                if($rows <= 0) $rows = $param['rows'];
                if($param_value == '') $param_value = $defvalue;
                $str = '<TEXTAREA NAME="param['.$pid.']" ROWS="'.$rows.'" COLS="'.$cols.'" class="textarea01">'.$param_value.'</TEXTAREA>';
            } elseif($param['type'] == 'checkbox') {
                $arr = explode('|', $defvalue);
                $arr = array_unique($arr);

                $val = explode('|', $param_value);
                $val = array_unique($val);


                $icount = 0;
                foreach($arr as $item) {
                    $item = trim(@(string)$item);
                    if($item != '') {
                        $checked = '';
                        foreach($val as $val1) {
                            $val1 = trim(@(string)$val1);
                            if($val1 == $item) {
                                $checked = 'checked';
                                break;
                            }
                        }
                        $str .= '<INPUT TYPE="checkbox" NAME="param['.$pid.'][]" id="param_'.$pid.'_'.$icount.'" value="'.$item.'" '.$checked.'> <label for="param_'.$pid.'_'.$icount.'">' . $item . '</label>&nbsp;';
                        $icount ++;
                    }
                }
            } elseif($param['type'] == 'radio') {
                $arr = explode('|', $defvalue);
                $arr = array_unique($arr);
                $icount = 0;
                foreach($arr as $item) {
                    $item = trim(@(string)$item);
                    if($item != '') {
                        $checked = ($param_value == $item) ? 'checked' : '';
                        $str .= '<INPUT TYPE="radio" NAME="param['.$pid.']" id="param_'.$pid.'_'.$icount.'" value="'.$item.'" '.$checked.'> <label for="param_'.$pid.'_'.$icount.'">' . $item . '</label>&nbsp;';
                        $icount ++;
                    }
                }
            } elseif($param['type'] == 'select') {
                $arr = explode('|', $defvalue);
                $arr = array_unique($arr);
                foreach($arr as $item) {
                    $item = trim(@(string)$item);
                    if($item != '') {
                        $selected = ($param_value == $item) ? 'selected' : '';
                        $str .= '<OPTION NAME="" value="'.$item.'" '.$selected.'> ' . $item . '</OPTION>';
                    }
                }
                $str = '<SELECT NAME="param['.$pid.']">' . $str . '</SELECT>';
            } elseif($param['type'] == 'file') {
                $str = '<INPUT TYPE="text" NAME="param['.$pid.']" VALUE="'.$param_value.'" size="60" class="text">' . 
                        '<INPUT TYPE="file" NAME="userdefparam_'.$pid.'" VALUE="" size="8" class="text" style="width:0px;">';
            }
            break;
        }
    }
    return $str;
}


function get_paramtype($typeid) {
    global $G_cfg;
    $str = '';
    $typeid = @(int)$typeid;
    foreach($G_cfg['article_cfg']['article_paramtype'] as $key => $param) {
        $select = ($key == @(int)$typeid) ? 'selected' : '';
        $text = '';
        if($param['type'] == 'text') {
            $text = '单行文本';
        } elseif($param['type'] == 'textarea') {
            $text = '多行文本';
        } elseif($param['type'] == 'checkbox') {
            $text = '多选按钮';
        } elseif($param['type'] == 'radio') {
            $text = '单选按钮';
        } elseif($param['type'] == 'select') {
            $text = '下拉选框';
        } elseif($param['type'] == 'file') {
            $text = '文件上传';
        } elseif($param['type'] == 'html') {
            $text = 'HTML编辑器';
        }
        $str   .= '<option value="' . $key . '" ' .$select .'>' . $text . '</option>';
    }
    return $str;
}
function paramli($cid) {
    global $_TABLES, $G_big_integer, $G_cfg;
    $tbl_article_class  = $_TABLES['article_class'];
    $tbl_article_param  = $_TABLES['article_param'];


    $str    = '';

    $conn   = & get_db_conn();
    $sql    = "SELECT * FROM $tbl_article_param WHERE cid=$cid ORDER BY paramorder ASC, id ASC";
    $rs     = &$conn->Execute($sql);
    if(!$rs->EOF) {
        while(!$rs->EOF) {
            $id = $rs->fields['id'];
            $paramname  = $rs->fields['paramname'];
            $paramorder = $rs->fields['paramorder'];
            $paramtype  = @(int)$rs->fields['paramtype'];
            $opt_paramtype  = get_paramtype($paramtype);
            $defvalue   = $rs->fields['defvalue'];
            $clos       = @(int)$rs->fields['clos'];
            $rows       = @(int)$rs->fields['rows'];
            $paramorder = ($paramorder >= $G_big_integer || $paramorder <= 0) ? '' : @(int)$paramorder;

            if($paramtype == 0 || $paramtype == 1 || $paramtype == 5 || $paramtype == 6) {
                if($paramtype == 0 || $paramtype == 5) {
                    if($clos <= 0) $clos = $G_cfg['article_cfg']['article_paramtype'][0]['size'];
                    $rows = '';
                } else {
                    if($clos <= 0) $clos = $G_cfg['article_cfg']['article_paramtype'][1]['cols'];
                    if($rows <= 0) $rows = $G_cfg['article_cfg']['article_paramtype'][1]['rows'];
                }
            } else {
                $rows = '';
                $clos = '';
            }


            $str   .= <<<EOT
<TR>
    <TD align="left"><input type="text" name="param_{$id}_paramname" id="param_{$id}_paramname" value="{$paramname}" size="20" class="text"><input type="hidden" name="param_{$id}" value="{$id}"></TD>
    <TD width="40"><input type="text" name="param_{$id}_paramorder" id="param_{$id}_paramorder" value="{$paramorder}" size="4" class="text" style="width:40px;" onkeypress="return non_num_filter(this);"></TD>
    <TD width="80"><select name="param_{$id}_paramtype" id="param_{$id}_paramtype">{$opt_paramtype}</select></TD>
    <TD width="100"><input type="text" name="param_{$id}_defvalue" id="param_{$id}_defvalue" value="{$defvalue}" size="12" class="text"></TD>
    <TD width="20"><input type="text" name="param_{$id}_clos" id="param_{$id}_clos" value="{$clos}" size="2" class="text" style="width:20px;" onkeypress="return non_num_filter(this);"></TD>
    <TD width="20"><input type="text" name="param_{$id}_rows" id="param_{$id}_rows" value="{$rows}" size="2" class="text" style="width:20px;" onkeypress="return non_num_filter(this);"></TD>
    <TD width="80" align="center">[<a href="javascript:void();" onclick="return param_modify('{$id}');">修改</a>]|[<a href="javascript:void();" onclick="return param_del('{$id}');">删除</a>]</TD>
</TR>
EOT;
            $rs->MoveNext();
        }
    }
    $opt_paramtype  = get_paramtype(0);
    $str    = <<<EOT
<TABLE border="0" cellpadding="2" cellspacing="2" width="100%" class="none_border">
<TR>
    <TD align="left"><B>参数名称</B></TD>
    <TD width="40"><B>排序</B></TD>
    <TD width="80"><B>表单类型</B></TD>
    <TD width="100"><B>默认值</B></TD>
    <TD width="20"><B>行</B></TD>
    <TD width="20"><B>列</B></TD>
    <TD width="80" align="center"><B>操作</B></TD>
</TR>
{$str}
<TR>
    <TD align="left"><input type="text" name="param_add_paramname" id="param_add_paramname" value="" size="20" class="text"></TD>
    <TD width="40"><input type="text" name="param_add_paramorder" id="param_add_paramorder" value="" size="4" class="text" style="width:40px;" onkeypress="return non_num_filter(this);"></TD>
    <TD width="80"><select name="param_add_paramtype" id="param_add_paramtype">{$opt_paramtype}</select></TD>
    <TD width="100"><input type="text" name="param_add_defvalue" id="param_add_defvalue" value="" size="12" class="text"></TD>
    <TD width="20"><input type="text" name="param_add_clos" id="param_add_clos" value="60" size="2" class="text" style="width:20px;" onkeypress="return non_num_filter(this);"></TD>
    <TD width="20"><input type="text" name="param_add_rows" id="param_add_rows" value="8" size="2" class="text" style="width:20px;" onkeypress="return non_num_filter(this);"></TD>
    <TD width="80" align="center">[<a href="javascript:void();" onclick="return param_add('{$cid}');">新增</a>]</TD>
</TR>
</TABLE>
EOT;
    return $str;
}


function articleparamli($cid, $aid) {
    global $_TABLES, $G_big_integer, $G_cfg, $class_var;
    $tbl_article_class  = $_TABLES['article_class'];
    $tbl_article_param  = $_TABLES['article_param'];
    $tbl_article_param_value = $_TABLES['article_param_value'];

    // 沿着路径找上去，直到找到有自定义参数的分类。
    $thiscid= 0;
    $arr    = tree_node_path($GLOBALS[$class_var], $cid);
    $arr    = array_reverse($arr);
    foreach($arr as $v) {
        if(@(int)$v['defparam'] == 1) {
            $thiscid = $v['__id__'];
            break;
        }
    }
    // 拆分开
    if($thiscid == 0) return '';


    $conn   = & get_db_conn();

    // 从 article_param_value 中读取当前文章的参数列表到数组中存起来
    $ars    = array();
    if($aid > 0) {
        $sql    = "SELECT * FROM $tbl_article_param_value WHERE aid = $aid ";
        $rs     = &$conn->Execute($sql);
        if(!$rs->EOF) $ars = $rs->GetRows();
    }

    $prs    = array();
    $sql    = "SELECT * FROM $tbl_article_param WHERE cid = $thiscid ORDER BY paramorder ASC, id ASC";
    $rs     = &$conn->Execute($sql);
    if(!$rs->EOF) $prs = $rs->GetRows();

    $str    = '';
    // 循环$prs
    foreach($prs as $param) {
        $pid        = $param['id'];
        $paramname  = $param['paramname'];
        $paramtype  = $param['paramtype'];
        $defvalue   = $param['defvalue'];
        $cols       = $param['clos'];
        $rows       = $param['rows'];

        $curvalue   = '';
        foreach($ars as $c) {
            if($c['pid'] == $pid) {
                $curvalue = $c['param_value'];
                break;
            }
        }
        $htmlparam  = get_paramhtml($pid, $paramtype, $curvalue, $defvalue, $cols, $rows);

        $str   .= <<<EOT
<TR>
	<TD width="120" align="right">{$paramname}：</TD>
	<TD>{$htmlparam}</TD>
</TR>
EOT;
    }

    $str = <<<EOT
<TABLE border="0" width="100%" cellpadding="1" cellspacing="1" class="none_border">
<TR>
	<TD width="120">参数名</TD>
	<TD>参数值</TD>
</TR>
$str
</TABLE>
EOT;
    return $str;
}


$action = trim(@$_GET['action']);

$tbl_article_param  = $_TABLES['article_param'];
$tbl_article_class  = $_TABLES['article_class'];
$tbl_paramval       = $_TABLES['article_paramval'];
if($action == 'paramli') {
    $cid = @(int)$_GET['cid'];
    echo paramli($cid);
    exit();
} elseif($action == 'paramadd') {
    $paramname  = trim($_POST['paramname']);
    $paramorder = @(int)$_POST['paramorder'];
    $paramtype  = @(int)$_POST['paramtype'];
    $defvalue   = trim($_POST['defvalue']);
    $clos       = @(int)$_POST['clos'];
    $rows       = @(int)$_POST['rows'];
    $cid        = @(int)$_GET['cid'];

    $paramorder = ($paramorder >= $G_big_integer || $paramorder <= 0) ? $G_big_integer : @(int)$paramorder;

    $conn   = & get_db_conn();
    // 检查该分类下是否有同名参数
    $sql    = iconv('UTF-8', 'GBK', "SELECT COUNT(*) AS rs_count FROM $tbl_article_param WHERE cid = '$cid' AND paramname = '$paramname' ");
    $rs     = $conn->GetRow($sql);
    if($rs['rs_count'] > 0) {
        echo 'samename';
        exit();
    }
    $sql    = iconv('UTF-8', 'GBK', "INSERT INTO $tbl_article_param (cid, paramname, paramorder, paramtype, defvalue, clos, rows) values 
                ('$cid', '$paramname', '$paramorder', '$paramtype', '$defvalue', '$clos', '$rows')");








    if($conn->Execute($sql)) {
        // 添加成功，说明该分类有自定义参数
        // defparam
        $id = $conn->Insert_ID();
        alterparam($id, $cid);

        $sql    = "UPDATE $tbl_article_class SET defparam = 1 WHERE cid = '$cid' ";
        $conn->Execute($sql);
        echo iconv('GBK', 'UTF-8', paramli($cid));
    } else {
        echo 'error';
    }
    exit();
} elseif($action == 'parammodify') {
    $paramname  = iconv('UTF-8', 'GBK', trim($_POST['paramname']));
    $paramorder = @(int)$_POST['paramorder'];
    $paramtype  = @(int)$_POST['paramtype'];
    $defvalue   = iconv('UTF-8', 'GBK', trim($_POST['defvalue']));
    $clos       = @(int)$_POST['clos'];
    $rows       = @(int)$_POST['rows'];
    $id         = @(int)$_POST['id'];

    $paramorder = ($paramorder >= $G_big_integer || $paramorder <= 0) ? $G_big_integer : @(int)$paramorder;

    $conn   = & get_db_conn();
    // 得到当前参数信息
    $sql    = "SELECT cid FROM $tbl_article_param WHERE id = '$id'";
    $param  = $conn->GetRow($sql);

    // 检查该分类下是否有同名参数
    $sql    = "SELECT COUNT(*) AS rs_count FROM $tbl_article_param WHERE cid = '{$param['cid']}' AND paramname = '$paramname' AND id <> '$id'";
    $rs     = $conn->GetRow($sql);
    if($rs['rs_count'] > 0) {
        echo 'samename';
        exit();
    }

    



    $sql    = "UPDATE $tbl_article_param SET
                        paramname = '$paramname',
                       paramorder = '$paramorder', 
                        paramtype = '$paramtype', 
                         defvalue = '$defvalue', 
                             clos = '$clos', 
                             rows = '$rows'
                            WHERE id = '$id'";
    //echo $sql;
    //exit();
    if($conn->Execute($sql)) {
        $sql    = "UPDATE $tbl_article_class SET defparam = 1 WHERE cid = '" . $param['cid'] . "' ";
        $conn->Execute($sql);
        alterparam($id, $param['cid']);
        echo iconv('GBK', 'UTF-8', paramli($param['cid']));
    } else {
        echo 'error';
    }
    exit();
} elseif($action == 'paramdel') {
    $id = @(int)$_POST['id'];
    $conn   = & get_db_conn();
    // 得到当前参数信息
    $sql    = "SELECT cid FROM $tbl_article_param WHERE id = '$id'";
    $param  = $conn->GetRow($sql);

    dropparam($id, $param['cid']);

    $sql    = "DELETE FROM $tbl_article_param WHERE id = '$id'";
    if($conn->Execute($sql)) {
        // 删除前看看是否删完了，如果删完了就设置 defparam = 0
        $sql    = "select count(*) AS rs_count FROM $tbl_article_param WHERE cid = '" . $param['cid'] . "' ";
        $rs     = $conn->GetRow($sql);
        if($rs && $rs['rs_count'] > 0) {} else {
            $sql    = "UPDATE $tbl_article_class SET defparam = 1 WHERE cid = '" . $param['cid'] . "' ";
            $conn->Execute($sql);
        }


        echo iconv('GBK', 'UTF-8', paramli($param['cid']));
    } else {
        echo 'error';
    }
    exit();
} elseif($action == 'articleparamlist') {
    // 读 article_param 将该分类下的自定义参数读出来，
    // 再读 article_param_value 将值填进去
    require($G_abs_includes . '/tree.lib.php');
    // 包含内容分类
    $file_name  = $cfg_cache['cache_abspath'] . '/' . 
                    $cfg_cache['content_class_cache_filename'];
    $class_var  = $cfg_cache['content_class_cache_var'];
    if(file_exists($file_name)) {
        require($file_name);
    } else {
        $$class_var = array();
    }


    $cid = @(int)$_GET['cid'];
    $aid = @(int)$_GET['aid'];
    echo iconv('GBK', 'UTF-8', articleparamli($cid, $aid));
    exit();
} elseif($action == 'articlelist') {
    require($G_abs_includes . '/article.libs.php');
    $cid            = @(int)$_GET['cid'];
    $page_size      = @(int)$_GET['page_size'];
    $modpath        = trim(@$_GET['modpath']);
    $title_length   = @(int)$_GET['title_length'];
    $orderby0       = @(int)$_GET['orderby0'];

 
    $param  = array(
        'page_size' => $page_size,
        'allow_page' => 0,
        'page' => 1,
        'modpath' => $modpath,
        'cid' => $cid,
        'title_length' => $title_length,
        'orderby0' => $orderby0, 
        );
    $list   = article_list($param);

    $str = '';
    foreach($list as $news) {
        $news['article_title']      = iconv('GBK', 'UTF-8', $news['article_title']);
        $news['article_title_cut']  = iconv('GBK', 'UTF-8', $news['article_title_cut']);

        $str .= <<<EOT
<TD align="left">
<table width="130" border="0" cellspacing="0" cellpadding="0" align="center">
  <tr>
    <td height="102" align="center" valign="middle"><a href="{$news['url_this_article']}" title="{$news['article_title']}" target="_blank"><img src="{$news['thumb_img']}" width="125" height="86" class="pad2 bor-solid bor1 bor-green1" /></a></td>
  </tr>
  <tr>
    <td align="center" valign="middle"><a href="{$news['url_this_article']}" title="{$news['article_title']}" target="_blank">{$news['article_title_cut']}</a></td>
  </tr>
</table></TD>
EOT;
    }
    $str = <<<EOT
<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
<TR>$str</TR>
</TABLE>
EOT;
    echo $str;
    exit();
}

function alterparam($pid, $cid) {
    global $_TABLES, $conn, $paramtype, $clos, $rows, $defvalue;
    $tbl_paramval   = $_TABLES['article_paramval'];

    // 向1:1表 prefix_article_paramval 中增加一个字段，名为“param_$cid”
    if($paramtype == 0 || $paramtype == 1) {
        if($paramtype == 0) $rows = 1;
        $fieldsize = $clos * $rows;
        if($fieldsize <= 0) $fieldsize = 100;
        if($fieldsize > 255) {
            $fieldtype = 'TEXT';
            $fielddef   = " NULL ";
        } else {
            $fieldtype = 'VARCHAR(' . $fieldsize . ')';
            $fielddef   = " NOT NULL DEFAULT '{$defvalue}' ";
        }
    } else {
        $fieldtype = 'INT';
        $fieldsize = 11;
        $fielddef   = " NOT NULL DEFAULT '0' ";;
        $fieldtype = 'INT(' . $fieldsize . ')';
    }



    // 处理自定义字段开始
    $field = "param_{$cid}_{$pid}";
    $chksql = "DESCRIBE $tbl_paramval $field ";
    $frs    = & $conn->GetRow($chksql);
    if($frs) {
        // 表中存在这样的字段
        $alter = "ALTER TABLE $tbl_paramval CHANGE $field $field {$fieldtype} {$fielddef}";
    } else {
        // 表中不存在这样的字段
        $alter = "ALTER TABLE {$tbl_paramval} ADD {$field} {$fieldtype} {$fielddef}";
    }
    $conn->Execute($alter);
    // 处理自定义字段结束

}


function dropparam($pid, $cid) {
    global $_TABLES, $conn;
    $tbl_paramval   = $_TABLES['article_paramval'];

    // 处理自定义字段开始
    $field = "param_{$cid}_{$pid}";
    $alter = "ALTER TABLE $tbl_paramval DROP $field ";
    $conn->Execute($alter);
    // 处理自定义字段结束
}




?>